<template>
	<view class="password-container">
		<!-- 顶部标题栏 -->
		<view class="password-header">
			<view class="header-left">
				<text class="header-title">密码发放管理</text>
				<text class="header-subtitle">教师打卡系统</text>
			</view>
			<image class="header-icon" src="/static/images/key-icon.png"></image>
		</view>

		<!-- 密码发放卡片 -->
		<view class="password-card">
			<view class="card-header">
				<text class="card-title">发放今日签到密码</text>
				<text class="card-date">{{ currentDate }}</text>
			</view>

			<!-- 密码输入区 -->
			<view class="password-input-section">
				<text class="section-title">签到密码</text>

				<!-- 密码显示框 -->
				<view class="password-display">
					<view class="password-digit" v-for="(digit, index) in passwordDigits" :key="index"
						:class="{'active': activeDigit === index}">
						{{ digit || '?' }}
					</view>
				</view>

				<!-- 操作按钮 -->
				<view class="action-buttons">
					<view class="action-btn generate" @click="generateRandomPassword">
						<uni-icons type="reload" size="24" color="#fff"></uni-icons>
						<text>随机生成</text>
					</view>
					<view class="action-btn confirm" @click="submitPassword">
						<uni-icons type="checkmarkempty" size="24" color="#fff"></uni-icons>
						<text>确认发放</text>
					</view>
				</view>
			</view>

			<!-- 数字键盘 -->
			<view class="number-keyboard">
				<view class="keyboard-row">
					<view class="key" v-for="num in [1,2,3]" :key="num" @touchstart="onKeyPress(num)"
						@touchend="clearActiveKey" :class="{'active': activeKey === num}">
						{{ num }}
					</view>
				</view>
				<view class="keyboard-row">
					<view class="key" v-for="num in [4,5,6]" :key="num" @touchstart="onKeyPress(num)"
						@touchend="clearActiveKey" :class="{'active': activeKey === num}">
						{{ num }}
					</view>
				</view>
				<view class="keyboard-row">
					<view class="key" v-for="num in [7,8,9]" :key="num" @touchstart="onKeyPress(num)"
						@touchend="clearActiveKey" :class="{'active': activeKey === num}">
						{{ num }}
					</view>
				</view>
				<view class="keyboard-row">
					<view class="key delete" @touchstart="onKeyPress('delete')" @touchend="clearActiveKey"
						:class="{'active': activeKey === 'delete'}">
						<uni-icons type="backspace" size="28" color="#666"></uni-icons>
					</view>
					<view class="key" @touchstart="onKeyPress(0)" @touchend="clearActiveKey"
						:class="{'active': activeKey === 0}">
						0
					</view>
					<view class="key clear" @touchstart="onKeyPress('clear')" @touchend="clearActiveKey"
						:class="{'active': activeKey === 'clear'}">
						<uni-icons type="trash" size="28" color="#666"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 教师列表 -->
		<view class="teacher-section">
			<view class="section-header">
				<text class="section-title">教师列表 ({{ teacherList.length }})</text>
				<view class="refresh-btn" @click="refreshData">
					<uni-icons type="refresh" size="24" color="#4D59FF"></uni-icons>
					<text>刷新</text>
				</view>
			</view>

			<view class="teacher-list">
				<view class="teacher-item" v-for="(teacher, index) in teacherList" :key="teacher.teacherId" :class="{
			        'selected': selectedTeacher === index,
			        'disabled': teacher.hasCode
			      }" @click="selectTeacher(index)">
					<image class="teacher-avatar" :src="teacher.avatarUrl || '/static/images/default-avatar.png'">
					</image>
					<view class="teacher-info">
						<text class="teacher-name">{{ teacher.name }}</text>
						<view class="teacher-meta">
							<text class="teacher-phone">{{ teacher.phone }}</text>
							<text class="teacher-grades">{{ teacher.grades }}</text>
						</view>
						<!-- 显示已发放的密码 -->
						<view v-if="teacher.hasCode" class="issued-password">
							<text class="password-text">已发放密码: {{ teacher.currentCode }}</text>
							<text class="issue-time">{{ teacher.createTime }}</text>
						</view>
					</view>
					<view class="teacher-status">
						<text class="status-text" :class="teacher.status">{{ teacher.statusText }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 操作结果提示 -->
		<uni-popup ref="resultPopup" type="message">
			<uni-popup-message :type="resultType" :message="resultMessage" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				currentDate: this.formatDate(new Date()),
				passwordDigits: ['', '', '', ''],
				activeDigit: 0,
				activeKey: null,
				teacherList: [],
				selectedTeacher: null,
				resultType: 'success',
				resultMessage: '',
				issuedCodes: [] // 存储已发放的密码记录
			};
		},
		async mounted() {
			await this.fetchIssuedCodes(); // 先获取已发放的密码记录
			await this.fetchTeachers();
		},
		methods: {
			// 刷新数据
			async refreshData() {
				uni.showLoading({ title: '刷新中...' });
				try {
					await this.fetchIssuedCodes();
					await this.fetchTeachers();
					this.showResult('success', '数据刷新成功');
				} catch (error) {
					this.showResult('error', '刷新数据失败');
				} finally {
					uni.hideLoading();
				}
			},
			
			// 获取已发放的密码记录
			async fetchIssuedCodes() {
				try {
					const res = await uni.request({
						url: `${globalVariable}/getAllTeacherCodeByDate?date=${this.currentDate}`,
						method: 'GET'
					});

					if (res.data.status === 1) {
						this.issuedCodes = res.data.data || [];
					}
				} catch (error) {
					console.error('获取已发放密码失败:', error);
					throw error;
				}
			},
			
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			onKeyPress(key) {
				this.activeKey = key;

				if (typeof key === 'number') {
					if (this.activeDigit < 4) {
						this.passwordDigits[this.activeDigit] = key.toString();
						if (this.activeDigit < 3) this.activeDigit++;
					}
				} else if (key === 'delete') {
					if (this.activeDigit > 0) {
						this.passwordDigits[this.activeDigit - 1] = '';
						this.activeDigit--;
					}
				} else if (key === 'clear') {
					this.passwordDigits = ['', '', '', ''];
					this.activeDigit = 0;
				}
			},

			clearActiveKey() {
				this.activeKey = null;
			},

			generateRandomPassword() {
				// 生成4位随机数字
				const randomPassword = Array.from({length: 4}, () => 
					Math.floor(Math.random() * 10).toString()
				);

				this.passwordDigits = randomPassword;
				this.activeDigit = 4; // 设置光标在最后

				// 播放生成音效
				uni.vibrateShort();
			},

			async fetchTeachers() {
				uni.showLoading({ title: '加载教师列表中...' });
				
				try {
					const res = await uni.request({
						url: `${globalVariable}/getAllTeachers`,
						method: 'GET'
					});
					
					if (res.data.status === 1) {
						this.teacherList = res.data.data.map(teacher => {
							// 检查该老师是否有当天的密码记录
							const issuedCode = this.issuedCodes.find(item => 
								item.teacherId === teacher.teacherId.toString()
							);
							
							return {
								...teacher,
								status: issuedCode ? 'success' : 'pending',
								statusText: issuedCode ? '已发放' : '待发放',
								hasCode: !!issuedCode, // 是否有密码记录
								currentCode: issuedCode ? issuedCode.code : null, // 已发放的密码
								createTime: issuedCode ? this.formatTime(new Date(issuedCode.createTime)) : null // 发放时间
							};
						});
					} else {
						throw new Error(res[0]?.message || '获取教师列表失败');
					}
				} catch (error) {
					console.error('获取教师列表失败:', error);
					this.showResult('error', error.message || '获取教师列表失败');
				} finally {
					uni.hideLoading();
				}
			},
			
			async submitPassword() {
				const password = this.passwordDigits.join('');
				
				if (password.length !== 4) {
					this.showResult('error', '请输入4位密码');
					return;
				}
				
				if (this.selectedTeacher === null) {
					this.showResult('error', '请选择一位教师');
					return;
				}
				
				const teacher = this.teacherList[this.selectedTeacher];
				
				// 再次检查是否已有密码
				if (teacher.hasCode) {
					this.showResult('warning', `${teacher.name}已有当日密码，无需重复发放`);
					return;
				}
				
				uni.showLoading({ title: '发放中...' });
				
				try {
					const res = await uni.request({
						url: `${globalVariable}/addCheckCode?teacherId=${teacher.teacherId}&teacherName=${encodeURIComponent(teacher.name)}&code=${password}&date=${this.currentDate}`,
						method: 'POST',
					});
					
					if (res.data.status === 1) {
						this.showResult('success', `密码已发放给${teacher.name}`);
						
						// 更新教师状态
						this.$set(this.teacherList[this.selectedTeacher], 'status', 'success');
						this.$set(this.teacherList[this.selectedTeacher], 'statusText', '已发放');
						this.$set(this.teacherList[this.selectedTeacher], 'hasCode', true);
						this.$set(this.teacherList[this.selectedTeacher], 'currentCode', password);
						this.$set(this.teacherList[this.selectedTeacher], 'createTime', this.formatTime(new Date()));
						
						// 添加到已发放记录
						this.issuedCodes.push({
							teacherId: teacher.teacherId.toString(),
							teacherName: teacher.name,
							code: password,
							date: this.currentDate,
							createTime: new Date().toISOString()
						});
						
						// 清空密码
						this.passwordDigits = ['', '', '', ''];
						this.activeDigit = 0;
					} else {
						throw new Error(res[0]?.message || '密码发放失败');
					}
				} catch (error) {
					console.error('密码发放失败:', error);
					this.$set(this.teacherList[this.selectedTeacher], 'status', 'error');
					this.$set(this.teacherList[this.selectedTeacher], 'statusText', '发放失败');
					this.showResult('error', error.message || '密码发放失败');
				} finally {
					uni.hideLoading();
				}
			},
			
			selectTeacher(index) {
				if (!this.teacherList[index].hasCode) {
					this.selectedTeacher = index;
				}
			},
			
			showResult(type, message) {
				this.resultType = type;
				this.resultMessage = message;
				this.$refs.resultPopup.open();
			},

			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			}
		}
	};
</script>

<style lang="scss" scoped>
	/* 颜色定义 */
	$primary-color: #4D59FF;
	$success-color: #4CAF50;
	$error-color: #F44336;
	$warning-color: #FFC107;
	$text-color: #333;
	$text-light: #666;
	$text-lighter: #999;
	$border-color: #eee;
	$bg-color: #f5f7fa;
	$card-bg: #fff;
	$shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
	$disabled-bg: #f9f9f9;

	.password-container {
		padding: 20rpx;
		background-color: $bg-color;
		min-height: 100vh;
	}

	/* 顶部标题 */
	.password-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		background: linear-gradient(135deg, $primary-color, #6A5ACD);
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		color: #fff;
		box-shadow: $shadow;

		.header-left {
			display: flex;
			flex-direction: column;
		}

		.header-title {
			font-size: 40rpx;
			font-weight: bold;
			margin-bottom: 10rpx;
		}

		.header-subtitle {
			font-size: 26rpx;
			opacity: 0.9;
		}

		.header-icon {
			width: 100rpx;
			height: 100rpx;
		}
	}

	/* 密码卡片 */
	.password-card {
		background-color: $card-bg;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: $shadow;

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 40rpx;
			padding-bottom: 20rpx;
			border-bottom: 1rpx solid $border-color;

			.card-title {
				font-size: 36rpx;
				font-weight: bold;
				color: $text-color;
			}

			.card-date {
				font-size: 28rpx;
				color: $text-light;
				background-color: rgba($primary-color, 0.1);
				padding: 6rpx 16rpx;
				border-radius: 20rpx;
			}
		}
	}

	/* 密码输入区 */
	.password-input-section {
		margin-bottom: 50rpx;

		.section-title {
			font-size: 28rpx;
			color: $text-light;
			display: block;
			margin-bottom: 20rpx;
		}

		.password-display {
			display: flex;
			justify-content: center;
			margin-bottom: 40rpx;

			.password-digit {
				width: 120rpx;
				height: 160rpx;
				margin: 0 10rpx;
				background-color: #f8f9fa;
				border-radius: 16rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 72rpx;
				font-weight: bold;
				color: $primary-color;
				box-shadow: inset 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
				transition: all 0.2s;

				&.active {
					background-color: rgba($primary-color, 0.1);
					box-shadow: 0 0 0 2rpx $primary-color;
				}
			}
		}

		.action-buttons {
			display: flex;
			justify-content: center;
			gap: 30rpx;

			.action-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 20rpx 40rpx;
				border-radius: 50rpx;
				font-size: 28rpx;
				font-weight: 500;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
				transition: all 0.2s;
				
				&:active {
					transform: scale(0.95);
				}

				uni-icons {
					margin-right: 10rpx;
				}

				&.generate {
					background: linear-gradient(135deg, $warning-color, #FF9800);
					color: #fff;
				}

				&.confirm {
					background: linear-gradient(135deg, $success-color, #2E7D32);
					color: #fff;
				}
			}
		}
	}

	/* 数字键盘 */
	.number-keyboard {
		background-color: $card-bg;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: $shadow;

		.keyboard-row {
			display: flex;
			justify-content: center;
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}
		}

		.key {
			width: 180rpx;
			height: 100rpx;
			margin: 0 10rpx;
			background-color: #f8f9fa;
			border-radius: 12rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 48rpx;
			font-weight: bold;
			color: $text-color;
			transition: all 0.1s;
			box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);

			&.active {
				background-color: rgba($primary-color, 0.2);
				transform: scale(0.95);
				box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
			}

			&.delete,
			&.clear {
				background-color: #f0f0f0;

				&.active {
					background-color: rgba($error-color, 0.2);
				}
			}
		}
	}

	/* 教师列表 */
	.teacher-section {
		background-color: $card-bg;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: $shadow;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;
			padding-bottom: 20rpx;
			border-bottom: 1rpx solid $border-color;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: $text-color;
			}
			
			.refresh-btn {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				color: $primary-color;
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				background-color: rgba($primary-color, 0.1);
				
				uni-icons {
					margin-right: 8rpx;
				}
			}
		}

		.teacher-list {
			.teacher-item {
				display: flex;
				align-items: center;
				padding: 25rpx 0;
				border-bottom: 1rpx solid $border-color;
				transition: all 0.2s;

				&:last-child {
					border-bottom: none;
				}

				&.selected {
					background-color: rgba($primary-color, 0.05);
					border-radius: 12rpx;
				}
				
				&.disabled {
					background-color: $disabled-bg;
					opacity: 0.8;
					
					.teacher-info {
						.teacher-name {
							color: $text-light;
						}
					}
				}

				.teacher-avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					margin-right: 20rpx;
					background-color: #f0f0f0;
					border: 2rpx solid $border-color;
				}

				.teacher-info {
					flex: 1;
					display: flex;
					flex-direction: column;

					.teacher-name {
						font-size: 28rpx;
						color: $text-color;
						margin-bottom: 5rpx;
						font-weight: bold;
					}

					.teacher-meta {
						display: flex;
						flex-direction: column;

						.teacher-phone {
							font-size: 24rpx;
							color: $text-light;
							margin-bottom: 5rpx;
						}

						.teacher-grades {
							font-size: 22rpx;
							color: $text-lighter;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							max-width: 300rpx;
						}
					}
					
					.issued-password {
						margin-top: 10rpx;
						display: flex;
						flex-direction: column;
						
						.password-text {
							font-size: 24rpx;
							color: $success-color;
							font-weight: bold;
						}
						
						.issue-time {
							font-size: 22rpx;
							color: $text-lighter;
						}
					}
				}

				.teacher-status {
					.status-text {
						font-size: 24rpx;
						padding: 6rpx 16rpx;
						border-radius: 20rpx;
						font-weight: bold;

						&.pending {
							color: $warning-color;
							background-color: rgba($warning-color, 0.1);
						}

						&.success {
							color: $success-color;
							background-color: rgba($success-color, 0.1);
						}

						&.error {
							color: $error-color;
							background-color: rgba($error-color, 0.1);
						}
					}
				}
			}
		}
	}
</style>